package com.oracle.lingshangejia.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.MyApp;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.FragmentAdapter;
import com.oracle.lingshangejia.base.BaseActivity;

import com.oracle.lingshangejia.bean.ThreeDoctorMyBean;
import com.oracle.lingshangejia.fragment.ConsultationFragment;
import com.oracle.lingshangejia.fragment.ConsultationFragmentRecord;
import com.oracle.lingshangejia.mvp.base.BaseFragment;
import com.oracle.lingshangejia.utils.AppManagerDelegate;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.SpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;

import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;

//专家端
public class ThreeDoctorMainActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIvHead;//头像
    private TextView tv_title;
    private ImageButton ib_back;
    private TextView tv_threedoctor_name;
    private TextView tv_threedoctor_phone;
    private TextView tv_threedoctor_zw; //主任医师
    private TextView tv_threedoctor_yy;  //医院
    private TextView tv_threedoctor_sj;  //三甲
   // private TextView tv_threedoctor_ly; //擅长领域
    private TextView tv_sign;//设置
    private int ysid;
    private AgoraAPIOnlySignal mAgoraAPI;
    private final int REQUEST_CODE = 0x01;
    private String mMyAccount;//我的手机号
    private boolean isShowNotification;//是否显示通知
    private ViewPager mViewPager;
    private TabLayout mTabLayout;




    @Override
    public int intiLayout() {
        return R.layout.activity_threedoctor;
    }

    @Override
    public void initView() {

        tv_title = findViewById(R.id.tv_title);
        ib_back = findViewById(R.id.ib_back);
        tv_sign = findViewById(R.id.tv_sign);
        tv_sign.setText("设置");
        tv_sign.setVisibility(View.VISIBLE);
        tv_sign.setOnClickListener(this);
        tv_threedoctor_name = findViewById(R.id.tv_threedoctor_name);
        tv_threedoctor_phone = findViewById(R.id.tv_threedoctor_phone);
        tv_threedoctor_zw = findViewById(R.id.tv_threedoctor_zw);
        tv_threedoctor_yy = findViewById(R.id.tv_threedoctor_yy);
        tv_threedoctor_sj = findViewById(R.id.tv_threedoctor_sj);
       // tv_threedoctor_ly = findViewById(R.id.tv_threedoctor_ly);
        mIvHead = (ImageView)findViewById(R.id.iv_head);
        ib_back.setVisibility(View.INVISIBLE);
        tv_title.setText("医生主页");
        mViewPager = findViewById(R.id.vp);
        mTabLayout = findViewById(R.id.tl);
        showLoading();



    }

    @Override
    public void initData() {
        List<String> title = new ArrayList<>();
        title.add("待办诊断");
        title.add("会诊记录");
        List<BaseFragment> fragmentList = new ArrayList<>();
        fragmentList.add(new ConsultationFragment());
        fragmentList.add(new ConsultationFragmentRecord());
        mViewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(),fragmentList ,title ));
        mTabLayout.setupWithViewPager(mViewPager);
        getNetToMy();
    }

    private void getNetToMy() {

        ysid = getIntent().getIntExtra("ysid", 0);
        HashMap<Object, Object> map = new HashMap<>();
        //map.put("mark", mark);
        map.put("userId", ysid);
        OkHttpUtils.getNetWork(this, Constant.baseurl + "online/user/getUserDetail", map, handler);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        String s = (String) msg.obj;
                        Gson gson = new Gson();
                        ThreeDoctorMyBean bean = gson.fromJson(s, ThreeDoctorMyBean.class);
                        if (bean.getCode() == 0) {
                            tv_threedoctor_name.setText(bean.getData().getName()); //名字
                            tv_threedoctor_phone.setText(bean.getData().getPhone());//手机号
                            tv_threedoctor_zw.setText(bean.getData().getKsmc());//科室
                            tv_threedoctor_yy.setText(bean.getData().getYymc());//医院
                           // tv_threedoctor_ly.setText(bean.getData().getSjysscly());

                            if (!TextUtils.isEmpty(bean.getData().getPicUrl())) {
                                RequestOptions requestOptions = new RequestOptions()
                                        .placeholder(R.drawable.ic_info_user)
                                        .circleCropTransform();
                                Glide.with(mIvHead.getContext()).load(Constant.imgurl+bean.getData().getPicUrl())
                                        .apply( requestOptions)
                                        .into(mIvHead);

                            }

                        } else {
                            Toast.makeText(ThreeDoctorMainActivity.this, bean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                        dismissLoading();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error = (String) msg.obj;
                    Toast.makeText(ThreeDoctorMainActivity.this, error, Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(ThreeDoctorMainActivity.this, "网络不可用", Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(ThreeDoctorMainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                break;
            case R.id.tv_sign:  //设置
                Intent intent = new Intent(ThreeDoctorMainActivity.this, SettingsActivity.class);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

    }

    private void addCallback() {

        MyApp.the().getmAgoraAPI().callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int i, int i1) {
                Log.i(TAG, "onLoginSuccess " + i + "  " + i1);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onLoginFailed(final int i) {
                Log.i(TAG, "onLoginFailed " + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {
                            //  ToastUtils.show(new WeakReference<Context>(LoginActivity.this), getString(R.string.str_msg_net_bad));
                        }
                    }
                });
            }


            @Override
            public void onError(String s, int i, String s1) {
                Log.i(TAG, "onError s:" + s + " s1:" + s1);
            }

        });


        if (mAgoraAPI == null) {
            return;
        }
        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLogout(final int i) {
                Log.i(TAG, "onLogout  i = " + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // other login the account
                            Toast.makeText(ThreeDoctorMainActivity.this, "Other login account, you are logout.", Toast.LENGTH_SHORT).show();

                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // net
                            Toast.makeText(ThreeDoctorMainActivity.this, "Logout for Network can not be.", Toast.LENGTH_SHORT).show();

                        }
                       // finish();
                    }
                });

            }


            @Override
            public void onLoginFailed(int i) {
                Log.i(TAG, "onLoginFailed  i = " + i);

            }

            @Override
            public void onInviteEndByPeer(final String channelID, String account, int uid, String s2) {
                Log.i(TAG, "onInviteEndByPeer channelID = " + channelID + " account = " + account);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        manager.cancelAll();
                    }
                });
            }

            //收到呼叫邀请回调
            @Override
            public void onInviteReceived(final String channelID, final String account, int uid, String s2) { //call out other remote receiver
                Log.i(TAG, "onInviteReceived  channelID = " + channelID + " account = " + account);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isShowNotification){
                            Intent intent = new Intent(ThreeDoctorMainActivity.this, CallActivity.class);
                            intent.putExtra("account", mMyAccount);//当前用户手机号
                            intent.putExtra("channelName", channelID);//频道号码 社区加上专家手机号
                            intent.putExtra("subscriber", account);   //社区医生手机号
                            intent.putExtra("type", Constant.CALL_IN);
                           // intent.putExtra("finish", "finish");
                            PendingIntent pendingIntent = PendingIntent.getActivity(ThreeDoctorMainActivity.this, REQUEST_CODE, intent, FLAG_UPDATE_CURRENT);

                            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                            String contentTitle = account+"向您发起视频"; //标题
                            Notification notification = new NotificationCompat.Builder(MyApp.getContext(),"").setContentTitle(contentTitle)
                                    .setContentText("").setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.icon_login)
                                    .setAutoCancel(true).setContentIntent(pendingIntent).setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.login_logo)).build();
                            manager.notify(1, notification);

                        }else {
                            Intent intent = new Intent(ThreeDoctorMainActivity.this, CallActivity.class);
                            intent.putExtra("account", mMyAccount);//当前用户手机号
                            intent.putExtra("channelName", channelID);//频道号码 社区加上专家手机号
                            intent.putExtra("subscriber", account);   //社区医生手机号
                            intent.putExtra("type", Constant.CALL_IN);
                            startActivityForResult(intent, REQUEST_CODE);
                        }
                    }
                });
            }

              ///当呼叫被对方收到时触发该回调。
      /*      @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver
                Log.i(TAG, "onInviteReceivedByPeer  channelID = " + channelID + "  account = " + account);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                      *//*  Intent intent = new Intent(ThreeDoctorMainActivity.this, CallActivity.class);
                        intent.putExtra("account", mMyAccount);
                        intent.putExtra("channelName", channelID);
                        intent.putExtra("subscriber", account);
                        intent.putExtra("type", Constant.CALL_OUT);
                        startActivityForResult(intent, REQUEST_CODE);*//*
                    }
                });

            }*/

            //如果呼叫失败，会回调 onInviteFailed。可能的原因有：
            //对方不在线
            //本端网络不通
           // 服务器异常
            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Log.i(TAG, "onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Log.e(TAG, "onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s.equals("query_user_status")) {
                            Toast.makeText(ThreeDoctorMainActivity.this, s1, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

         /*   @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Log.i(TAG, "onQueryUserStatusResult name = " + name + " status = " + status);
               // 该回调返回用户状态查询结果
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }*/

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult requestCode: " + requestCode + " resultCode: " + resultCode);
       /* if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getStringExtra("result").equals("finish")) {
                finish();
            }
        }*/
        if (requestCode == 1 && resultCode ==2){
            AppManagerDelegate.getInstance().finishActivity(ThreeDoctorMainActivity.class);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isShowNotification = false;
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        String username = (String) SpUtils.get(ThreeDoctorMainActivity.this, "sj_phone", "");
        mMyAccount = username;
        if (mAgoraAPI != null){ ;
            if (mAgoraAPI.getStatus() != 2) {
                MyApp.the().getmAgoraAPI().login2(getString(R.string.agora_app_id), username, "_no_need_token", 0, "", 5, 1);
            }
            addCallback();
            StringBuffer version = new StringBuffer("" + MyApp.the().getmAgoraAPI().getSdkVersion());
            if (version.length() >= 8) {
                String strVersion = "version " + version.charAt(2) + "." + version.charAt(4) + "." + version.charAt(6);
                Log.e("version", strVersion);
            }
        }



    }

    @Override
    protected void onStop() {
        super.onStop();


    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        MyApp.logout();

    }

   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/
    private static long lastBackTime = 0;//上一次点击 back 键的时间,用于双击退出的判断
    private final int BACK_INTERVAL = 1000;//当双击 back 键在此间隔内是直接触发 onBackPressed
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastBackTime < BACK_INTERVAL) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "双击 back 退出", Toast.LENGTH_SHORT).show();
        }
        lastBackTime = currentTime;
    }

}

